<!-- 产品碳足迹-模型搭建-输入输出表单-添加因子 -->

<template>
  <div class="">
    <section class="cardBox" style="">
      <div class="table-page-search-wrapper">
        <a-form-model :model="queryParam" layout="inline">
          <a-form-model-item :label="$t('message.Factor_name')" required>
            <a-input v-model="queryParam.name" allowClear :placeholder="$t('message.Please_enter')" :maxLength="32"></a-input>
          </a-form-model-item>
          <a-form-model-item :label="$t('message.Factor_unit')" required>
            <div class="m_cFlex">
              <a-select v-model="queryParam.numeratorUnitId" :placeholder="$t('message.Please_select')" show-search
                        :filter-option="filterOption" @change="onChangeNumeratorUnitId">
                <a-select-option :value="item.id" v-for="(item,index) in fzData" :key="index">
                  {{ item.factorUnit }}
                </a-select-option>
              </a-select>
              <span style="margin: 0 10px;">/</span>
              <a-select v-model="queryParam.denominatorUnitId" :placeholder="$t('message.Please_select')" show-search
                        :filter-option="filterOption" @change="onChangeDenominatorUnitId">
                <a-select-option :value="item.id" v-for="(item,index) in fmData" :key="index">
                  {{ item.unitCode }}
                </a-select-option>
              </a-select>
            </div>
          </a-form-model-item>

          <a-form-model-item :label="$t('message.Factor_description')">
            <a-input v-model="queryParam.instruction" allowClear :placeholder="$t('message.Please_enter')" :maxLength="512"></a-input>
          </a-form-model-item>
          <a-form-model-item :label="`${$t('message.Factor_value')}（${$t('message.Carbon_dioxide_equivalent')}）`" required>
            <div class="m_cFlex">
              <a-input-number v-model="queryParam.factorValue" :step="0.0001" :precision="4"
                              :disabled="queryParam.computerType == 2" allowClear :placeholder="$t('message.Please_enter')"
                              style="width: 200px"/>
              <div class="switchBtn m_hoverCP" @click="onChangeComputerType "
                   v-if="queryParam.computerType == 1">
                <img class="switchBtn_icon " src="@assets/img/img29.png" alt=""/>{{$t('message.Switch_ratio_calculation')}}
              </div>
              <div class="switchBtn m_hoverCP" @click="queryParam.computerType = 1"
                   v-if="queryParam.computerType == 2">
                <img class="switchBtn_icon " src="@assets/img/img29.png" alt=""/>{{$t('message.Switch_manual_transmission')}}
              </div>
            </div>
          </a-form-model-item>
        </a-form-model>
      </div>
      <div style="margin-top: 20px;" v-if="queryParam.computerType == 2">
        <a-table :columns="columns" :dataSource="queryParam.gasList" :pagination="false" :bordered="false"
                 size="middle">
          <template slot="gasName" slot-scope="text, record">
            <a-select v-model="record.gasName" :placeholder="$t('message.Please_select')" show-search :filter-option="filterOption"
                      @change="onChangeGas($event,record)" style="width: 100%;">
              <a-select-option :value="item.gasName" :disabled="item.disabled" v-for="(item,index) in gasData"
                               :key="item.gasName">
                {{ item.gasName }}
              </a-select-option>
            </a-select>
          </template>
          <template slot="factorValue" slot-scope="text, record">
            <a-input-number v-model="record.factorValue" :step="0.0001" :precision="4" :placeholder="$t('message.Please_enter')"
                            @change="computeFactorValue" style="width: 100%;"/>
          </template>
          <template slot="gwpValue" slot-scope="text, record">
            <a-input-number v-model="record.gwpValue" :step="0.01" :precision="4" :placeholder="$t('message.Please_enter')"
                            @change="computeFactorValue" style="width: 100%;"/>
          </template>
          <div class="m_ccFlex" slot="action" slot-scope="text, record, index">
            <a-popconfirm :title="$t('message.Confirm_delete')" :cancelText="$t('message.Cancel')" 
              :okText="$t('message.Confirm')" @confirm="() => onDel(index)">
              <a>{{$t('message.Delete')}}</a>
            </a-popconfirm>
          </div>
        </a-table>
        <div class="addBtn m_hoverCP" @click="onAdd">
          <img class="addBtn_icon " src="@assets/img/img30.png" alt=""/>{{$t('message.Add_gas')}}
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import Vue from "vue";
import {ACCESS_TOKEN} from "@/store/mutation-types";
import {getAction, postAction} from "@api/manage";

export default {
  components: {},
  data() {
    return {
      columns: [
        {
          title: this.$t('message.greenhouse_gas'),
          align: "center",
          dataIndex: "gasName",
          width: 100,
          scopedSlots: {customRender: "gasName"},
        },
        {
          title: this.$t('message.Factor_value'),
          align: "center",
          dataIndex: "factorValue",
          width: 100,
          scopedSlots: {customRender: "factorValue"},
        },
        {
          title: this.$t('message.Factor_molecular_unit'),
          align: "center",
          dataIndex: "molecularUnit",
          width: 100,
        },
        {
          title: this.$t('message.Factor_denominator_unit'),
          align: "center",
          dataIndex: "denominatorUnit",
          width: 100,
        },
        {
          title: this.$t('message.GWP_value'),
          align: "center",
          dataIndex: "gwpValue",
          width: 100,
          scopedSlots: {customRender: "gwpValue"},
        },
        {
          title: this.$t('message.Handle'),
          align: "center",
          width: 100,
          scopedSlots: {customRender: "action"},
        },
      ],
      queryParam: {
        gasList: [],
        computerType: 1, // 类型（1=手动输入，2=配比计算）
        type: "2", // 数据库,默认组织因子库,不可更改（1=碳排因子库，2=组织因子库）
      },
      fzData: [], // 因子分子数据
      fmData: [], // 因子分母数据
      gasData: [], // 气体数据
      allGasData: [], // 气体二位数组数据
    };
  },
  computed: {},
  watch: {
    "queryParam.gasList": {
      deep: true,
      handler(val, oldVal) {
        // console.log('watch =>', val, oldVal)
        let keyData = [];
        val.forEach((item) => {
          if (item.gasName) {
            keyData.push(item.gasName);
          }
        });
        // console.log('watch keyData =>', keyData)
        this.gasData.forEach((item) => {
          if (keyData.includes(item.gasName)) {
            this.$set(item, "disabled", true);
          } else {
            this.$set(item, "disabled", false);
          }
        });
        // console.log('watch gasData =>', this.gasData)
      },
    },
  },
  created() {
    this.getData();
  },
  methods: {
    /**
     * 配比计算-根据气体计算因子值
     */
    computeFactorValue() {
      let data = 0;
      this.queryParam.gasList.forEach((item) => {
        let factorValue = item.factorValue ? Number(item.factorValue) : 0;
        let gwpValue = item.gwpValue ? Number(item.gwpValue) : 0;
        data = data + factorValue * gwpValue;
      });
      this.$set(this.queryParam, "factorValue", Number(data.toFixed(4)));
    },
    onChangeComputerType() {
      if (this.queryParam.computerType == 1) {
        // 从手动切换到配比计算
        this.queryParam.computerType = 2;
        this.onChangeNumeratorUnitId(this.queryParam.numeratorUnitId)
      } else if (this.queryParam.computerType == 2) {
        // 从配比计算切换到手动
        this.queryParam.computerType = 1;
      }
      this.queryParam.gasList = [];
      this.computeFactorValue();
    },
    /**
     * 修改分子单位，同时删除温室气体
     */
    onChangeNumeratorUnitId(value) {
      console.log("onChangeNumeratorUnitId", value);
      let theIndex = this.fzData.findIndex((ele) => ele.id == value);
      if (theIndex > -1) {
        this.$set(this.queryParam, "numeratorUnit", this.fzData[theIndex].factorUnit);
        this.gasData = this.allGasData[theIndex]
        if (this.queryParam.gasList && this.queryParam.gasList.length > 0) {
          this.queryParam.gasList.forEach((gasItem, gasIndex) => {
            this.gasData.forEach((gasItem2, gasIndex2) => {
              if (gasItem.gasName === gasItem2.gasName) {
                console.log('gasItem2', gasItem2)
                gasItem.molecularUnit = gasItem2.gasUnit
              }
            })
          })
        }
        this.computeFactorValue()
      }
    },
    /**
     * 修改分母单位，同时修改所有温室气体的因子分母单位
     */
    onChangeDenominatorUnitId(value) {
      console.log("onChangeDenominatorUnitId", value);
      let theIndex = this.fmData.findIndex((ele) => ele.id == value);
      if (theIndex > -1) {
        this.$set(this.queryParam, "denominatorUnit", this.fmData[theIndex].unitCode);
        this.queryParam.gasList.forEach((item) => {
          this.$set(item, 'denominatorUnit', this.fmData[theIndex].unitCode)
        });
      }
    },
    /**
     * 添加气体
     */
    onAdd() {
      console.log("onAdd");
      let obj = {};
      if (this.queryParam.denominatorUnitId) {
        obj.denominatorUnit = this.queryParam.denominatorUnit;
      }
      this.queryParam.gasList.push(obj);
    },
    /**
     * 删除气体
     */
    onDel(index) {
      console.log("onAdd");
      this.queryParam.gasList.splice(index, 1);
      this.computeFactorValue();
    },
    /**
     * 修改气体
     * @param e
     * @param record
     */
    onChangeGas(e, record) {
      console.log("onChangeGas", e, record);
      let theIndex = this.gasData.findIndex((ele) => ele.gasName == e);
      if (theIndex > -1) {
        this.$set(record, "molecularUnit", this.gasData[theIndex].gasUnit);
        this.$set(record, "gwpValue", this.gasData[theIndex].gwpValue);
        this.computeFactorValue();
      }
    },
    /**
     * 检查表单数据
     */
    checkFormData() {
      if (!this.queryParam.name) {
        this.$message.warn(this.$t('message.please_enter_factor_name'))
        return false;
      }
      if (!this.queryParam.numeratorUnitId) {
        this.$message.warn(this.$t('message.please_select_the_factor_molecular_unit'))
        return false;
      }
      if (!this.queryParam.denominatorUnitId) {
        this.$message.warn(this.$t('message.please_select_factor_denominator_unit'))
        return false;
      }
      if (this.queryParam.computerType == 1) {
        // 手动输入
        if (!this.queryParam.factorValue || (this.queryParam.factorValue && this.queryParam.factorValue < 0)) {
          this.$message.warn(this.$t('message.please_enter_a_factor_value_co2_equivalent_greater_than_0'))
          return false
        }
      }
      if (this.queryParam.computerType == 2) {
        // 手动输入
        if (!this.queryParam.gasList || (this.queryParam.gasList && this.queryParam.gasList.length == 0)) {
          this.$message.warn(this.$t('message.please_add_at_least_one_gas'))
          return false
        }
        let errorIndex = null
        let errorType = null
        for (let i = 0; i < this.queryParam.gasList.length; i++) {
          let theObj = this.queryParam.gasList[i]
          if (!theObj.gasName) {
            errorIndex = i
            errorType = "gasName"
            break
          }
          if (!theObj.factorValue || (theObj.factorValue && theObj.factorValue < 0)) {
            errorIndex = i
            errorType = "factorValue"
            break
          }
          if (!theObj.gwpValue) {
            errorIndex = i
            errorType = "gwpValue"
            break
          }
        }
        if (errorType === "gasName") {
          this.$message.warn(this.$t('message.please_select_gas'))
          return false
        }
        if (errorType === "factorValue") {
          this.$message.warn(this.$t('message.please_enter_a_factor_value_greater_than_0'))
          return false
        }
        if (errorType === "gwpValue") {
          this.$message.warn(this.$t('message.please_enter_gwp_value'))
          return false
        }
      }
      return true
    },
    /**
     * 提交
     */
    onSubmit() {
      console.log("queryParam", this.queryParam);
      if (this.checkFormData()) {
        postAction("/footprintProduct/cyFootprintProduct/addEmissionByCarbonCheck", this.queryParam).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('message.operation_success'))
            this.onBack();
          }
        });
      }
    },
    getData() {
      // 分子
      getAction("/CyFactorUnit/cyFactorUnit/list").then((res) => {
        if (res.success) {
          this.fzData = res.result.records || [];
          this.allGasData = []
          this.fzData.forEach((item, index) => {
            getAction('/gas/cyGasStore/listGasName', {
              factorRealUnit: item.factorRealUnit
            }).then((res) => {
              if (res.success) {
                this.allGasData[index] = res.result || []
              }
            });
          })
        }
      });
      // 分母
      getAction("/emission/factor/cyEmissionUnit/getAllUnit").then((res) => {
        if (res.success) {
          this.fmData = res.result || [];
        }
      });
    },
    // ==============================================================================
    /**
     * 下拉框数据过滤
     */
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    /**
     * 返回
     */
    onBack() {
      this.$emit('back')
    },
  },
};
</script>

<style lang="less" scoped>

.cardHeader {
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #000000;

  .cardHeader_icon {
    width: 16px;
    height: 16px;
  }
}

.cardBox {
  overflow: hidden;
  padding: 32px 24px 12px;
  background: #ffffff;
  border-radius: 3px;

  .cardBox_title {
    margin-bottom: 24px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 20px;
    color: #333333;
  }
}

.switchBtn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-left: 8px;
  padding: 0 16px;
  height: 32px;
  background: #ffffff;
  border-radius: 3px;
  border: 1px solid #148958;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #148958;
  white-space: nowrap;

  .switchBtn_icon {
    width: 16px;
    height: 16px;
  }
}

.addBtn {
  margin-top: 16px;
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 112px;
  height: 32px;
  background: #ffffff;
  border-radius: 3px;
  border: 1px solid #148958;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #148958;

  .addBtn_icon {
    width: 16px;
    height: 16px;
  }
}

.uploadBtn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 112px;
  height: 32px;
  background: #ffffff;
  border-radius: 3px;
  border: 1px solid #dcdcdc;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #148958;

  .uploadBtn_icon {
    width: 16px;
    height: 16px;
  }
}

.optionBox {
  margin-top: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 24px;

  .optionItem {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 103px;
    height: 32px;
    border-radius: 3px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
  }

  .optionItem_cancel {
    background: #e7e7e7;
    color: rgba(0, 0, 0, 0.9);
  }

  .optionItem_confirm {
    background: #148958;
    color: rgba(255, 255, 255, 0.9);
  }
}
</style>
  